import { Request, Response, NextFunction } from 'express';
import path from 'path';
import fs from 'fs';
import _ from 'lodash';
import { getMovice, createMovie, updateHouse, deleteMovie, getIdHouse, houseStatusChange, createFile, updateFile, findFileById, deleteFileById, byKeyWordSelect, createMultisetMovie, updateMultisetMovie, getMovieById, getRecentlyMovie, getRandomHouse } from './house.service';
import { getFavorite } from '../favorites/favorites.service';
import { createNotice } from '../notification/notification.service';
import { getUserOrder } from '../order/order.service';
import { createUserAuth, reduceSendAuth, selectUserAuth } from '../user_auth/user_auth.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = request.query.status
  let is_multiset = request.query.is_multiset
  let countryId = request.query.countryId
  let pageNo = request.query.pageNo
  let pageSize = request.query.pageSize
  let is_free = request.query.is_free
  let recommend = request.query.recommend;
  let play_year = request.query.play_year;
  let popular = request.query.popular;
  let language_type = request.query.language_type;
  let categoryId = request.query.categoryId;
  let keyWord = request.query.keyWord;

  if (request.query.recommend as any == 1) {
    (recommend as any) = 1
  } else {
    (recommend as any) = -1
  }

  if (request.query.popular as any == 1) {
    (popular as any) = 1
  } else {
    (popular as any) = -1
  }
  
  const data = await getMovice(
    parseInt(`${status}`, 10),
    parseInt(`${is_multiset}`, 10),
    parseInt(`${recommend}`, 10),
    parseInt(`${countryId}`, 10),
    parseInt(`${popular}`),
    parseInt(`${pageSize}`),
    parseInt(`${pageNo}`, 10),
    -1,
    parseInt(`${is_free}`, 10),
    parseInt(`${play_year}`, 10),
    parseInt(`${language_type}`, 10),
    parseInt(`${categoryId}`, 10),
    keyWord,
  );
 
  response.send(data);
}

/**
 * 随机获取电影
 */
export const random = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = 1;
  let pageSize = request.query.pageSize;
  let recommend = request.query.recommend;
  let categoryId = request.query.categoryId;

  const data = await getRandomHouse(
    parseInt(`${categoryId}`, 10),
    parseInt(`${recommend}`, 10),
    parseInt(`${status}`, 10),
    parseInt(`${pageSize}`),
  );

  response.send(data);
};

/**
 * 获取内容(按 ID 查找)
 */
export const houseDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 是否可放
  let isPlay = false;

  try {
    const data = await getIdHouse(parseInt(postId, 10));

    // 如果电视剧直接返回，免费观看第一集
    if (data.is_multiset == 1) {
      isPlay = true;
      return response.send({ data, isPlay });
    }

    if (request.user !== undefined) {
      // 用户 ID
      let user_id = request.user.id;

      // 检查是否有会员
      let isVipUser = await selectUserAuth(user_id);

      // 当前时间
      let theTime = parseInt(`${new Date().getTime()}`, 10)

      // 结束时间
      let endTime = 0;
      if (isVipUser[0] !== undefined && isVipUser[0].endTime) endTime = isVipUser[0].endTime;

      if (data.is_free == 1) {
        // 判断让不让播放
        if (endTime - theTime > 0) isPlay = true
      } else if (data.is_free == 0) isPlay = true

      // 做出响应
      return response.send({ data, isPlay });
    }

    // 做出响应
    response.send({ data, isPlay });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取内容(按 ID 查找) 后台专用
 */
export const movieDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.body;

  try {
    const data = await getMovieById(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取最新电影
 */
export const recentlyMovive = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取最近影片时间
  const { pageNo } = request.body;
  const { pageSize } = request.body;
  const { playTime } = request.body;

  try {
    const data = await getRecentlyMovie(parseInt(`${playTime}`, 10), parseInt(`${pageNo}`, 10), parseInt(`${pageSize}`, 10));

    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 模糊查询
 */
export const selectByKey = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取查询关键字
  const { keyWord } = request.query;

  try {
    const data = await byKeyWordSelect(keyWord)
    response.send(data);
  } catch (error) {
    next();
  }
}

/**
 * 创建电影内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let moviceModal = request.body;
  
  moviceModal.status = 1;
  let releaseTime = Math.floor(new Date().getTime())
  moviceModal.releaseTime = releaseTime;
    
  // 创建内容
  if (moviceModal.id && moviceModal.id > 0) {
    
    if (moviceModal.is_multiset == 1) {
      let multisetsData = moviceModal.multiSet;
      let moviceData = moviceModal;
      delete moviceData.multiSet;

      await updateHouse(moviceData, parseInt(moviceData.id, 10));

      // 创建多集内容
      for (let item of multisetsData) {
        if (!item.id) {
          await createMultisetMovie(item);
        } else {
          await updateMultisetMovie(item, parseInt(item.id, 10))
        }
      };

      response.send({ status: 200, msg: 'success' });
    } else {
      const data = await updateHouse(moviceModal, parseInt(moviceModal.id, 10));
      response.send(data);
    }

  } else {
    // 判断是否多集
    if (moviceModal.is_multiset == 1) {
      let multisetsData = moviceModal.multisets;
      let moviceData = moviceModal;
      delete moviceData.multisets
      const data = await createMovie(moviceData);

      // 创建多集内容
      for (let item of multisetsData) {
        item.movie_id = (data as any).insertId;
        await createMultisetMovie(item);
      }

      // 返回数据
      response.send(data);

    } else {
      const data = await createMovie(moviceModal);

      // 返回数据
      response.send(data);
    }
    
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 更新内容
  const post = _.pick(request.body, [
    'status',
    'attributes',
    'type',
    'name',
    'url',
    'score',
    'star',
    'is_free',
    'content'
  ]);

  // 更新内容
  try {
    const data = await updateHouse(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  // const { postId } = request.params;
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteMovie(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error)
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const { postId } = request.body;

  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await houseStatusChange(parseInt(postId, 10), post);
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
    let { target_type, target_id } = request.body;
    if (target_id === undefined) {
      target_type = request.query.target_type;
      target_id = request.query.target_id;
    }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/houses/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);
  
  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      ...request.fileMataData,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })
    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const houseData = await updateHouse(post as any, parseInt(`${target_id}`, 10));
    
    // 做出响应
    response.status(200).send(houseData)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 要提供的图像尺寸
    const { size } = request.query;

    // 文件名与目录
    let filename = file[0].filename;
    let root = 'uploads/houses/resized';
    let resized = 'resized';

    if (size) {
      // 可用的图像尺寸
      const imageSize = ['lerge', 'medium', 'thumbnail'];

      // 检查文件尺寸是否可用
      if (!imageSize.some(item => item == size)) {
        throw new Error('FILE_NOT_FOUND');
      }

      // 检查文件是否存在
      const fileExist = fs.existsSync(
        path.join(root, resized, `${filename}-${size}`),
      )

      // 设备文件名与目录
      if (fileExist) {
        filename = `${filename}-${size}`;
        root = path.join(root, resized);
      }
    }

    // 做出响应
    response.sendFile(filename, {
      root,
      headers: {
        'Content-Type': file[0].mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])
  
  response.send({
    result,
    status: 1,
    msg: 'ok'
  })

}
